<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="企业名称" prop="tenantId">
        <el-select filterable v-model="queryParams.tenantId" @change="getSubtenantList(1,$event)" placeholder="请选择企业名称" clearable size="small">
          <el-option v-for="dict in tenantList" :key="parseInt(dict.id)" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="分公司名称" prop="subTenantId">
        <el-select filterable v-model="queryParams.subTenantId" @change="getByIdStoreList" placeholder="请选择分公司名称" clearable size="small">
          <el-option v-for="dict in subtenantList" :key="parseInt(dict.id)" :label="dict.name" :value="parseInt(dict.id)" />
        </el-select>
      </el-form-item>
      <el-form-item label="门店名称" prop="id">
        <el-input v-model="queryParams.name" placeholder="请输入门店名称" clearable />
        <!-- <el-select v-model="queryParams.id" placeholder="请选择门店名称" clearable size="small">
          <el-option v-for="dict in storeList" :key="parseInt(dict.id)" :label="dict.name" :value="dict.id" />
        </el-select> -->
      </el-form-item>
      <el-form-item label="门店编码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入门店编码" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="getTableData">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button plain type="primary" icon="el-icon-plus" size="small" @click="openDialog">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-upload2" size="small" @click="handleImportStore">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="small" @click="exportList">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getTableData"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableData">
      <el-table-column label="操作" align="center" fixed="left" width="100">
        <template v-slot="scope">
          <el-button size="small" icon="el-icon-edit" type="text" @click="handleUpdate(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
      <el-table-column label="门店名称" prop="name" align="center" fixed="left" />
      <el-table-column label="门店编码" prop="code" align="center" />
      <el-table-column label="商户名称" prop="tenantName" align="center" />
      <el-table-column label="商户类型" prop="type" align="center">
        <template v-slot="scope">
          <dict-tag :type="DICT_TYPE.app_account_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="分公司名称" prop="subTenantName" align="center" />
      <el-table-column label="店长姓名" prop="userName" align="center" />
      <el-table-column label="状态" prop="status" align="center">
        <template v-slot="scope">
          <el-switch @change="changeSwitch(scope.row)" v-model="scope.row.status" :active-value="0" :inactive-value="1" />
        </template>
      </el-table-column>
      <el-table-column label="联系方式" prop="phone" align="center" />
      <el-table-column label="邮箱" prop="email" align="center" />
      <el-table-column label="更新时间" prop="updateTime" align="center">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize" @pagination="getTableData" />

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="900px" v-dialogDrag append-to-body>
      <el-form :model="dialogParams" ref="dialogParams" :inline="true" :rules="rules" label-width="140px">
        <el-form-item label="商户类型" prop="type">
          <el-input :value="'企业'" :disabled="true" placeholder="请输入商户类型" style="width: 240px" clearable />
        </el-form-item>
        <el-form-item label="商户名称" prop="tenantId">
          <el-select :disabled="dialogParams.id?true:false" style="width: 240px" v-model="dialogParams.tenantId" @change="getSubtenantList(2,$event)" placeholder="请选择商户名称" clearable size="small">
            <el-option v-for="dict in tenantList" :key="parseInt(dict.id)" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="分公司名称" prop="subTenantId">
          <el-select :disabled="dialogParams.id?true:false" style="width: 240px" v-model="dialogParams.subTenantId" placeholder="请选择分公司名称" clearable size="small">
            <el-option v-for="dict in subtenantList" :key="parseInt(dict.id)" :label="dict.name" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="门店名称" prop="name">
          <el-input v-model="dialogParams.name" placeholder="请输入门店名称" style="width: 240px" clearable />
        </el-form-item>
        <el-form-item label="门店地址" prop="address">
          <el-input v-model="dialogParams.address" placeholder="请输入分公司地址" style="width: 240px" clearable />
        </el-form-item>
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input v-model="dialogParams.creditCode" placeholder="请输入统一社会信用代码" style="width: 240px" maxlength="18" clearable />
        </el-form-item>
        <el-form-item label="营业执照" prop="licence">
          <div style="width: 240px">
            <imageUpload :limit="1" v-model="dialogParams.licence" />
          </div>
        </el-form-item>
        <el-form-item label="店长姓名" prop="userName">
          <el-input v-model="dialogParams.userName" placeholder="请输入联系人" style="width: 240px" clearable />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="dialogParams.phone" placeholder="请输入联系方式" style="width: 240px" clearable maxlength="11" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="dialogParams.email" placeholder="请输入邮箱" style="width: 240px" clearable />
        </el-form-item>
        <!-- <el-form-item label="账户名" prop="accountName">
          <el-input v-model="dialogParams.accountName" placeholder="请输入账户名" style="width: 240px" clearable />
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="dialogParams.account" placeholder="请输入账号" style="width: 240px" clearable />
        </el-form-item>
        <el-form-item label="开户行" prop="bank">
          <el-input v-model="dialogParams.bank" placeholder="请输入开户行" style="width: 240px" clearable />
        </el-form-item>-->
      </el-form>
      <div style="display: flex; justify-content: flex-end">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <importUploadFile :visible.sync="visibleImportFile" :fetchFun="fetchFunImport" :importTemplate="importTemplate" @done="getTableData" templateTitle="门店导入模板" />
  </div>
</template>

<script>
import { businessListsAll, subtenantListsAll } from '@/api/merchantManagement/business';
import ImageUpload from '@/components/ImageUpload'
import ImagePreview from '@/components/ImagePreview'
import { getCompanyByType, byIdGetBranchCom } from "@/api/merchantManagement/branchCompany";
import { getStoreList, getStoreBySuTenantId, addStoreInfo, updateStoreInfo, exportStoreList, importStoreList, importStoreTemplate } from "@/api/merchantManagement/store";
import { validMobile, validEmails, validCreditCode } from '@/utils/validate'
import importUploadFile from "@/components/importUploadFile";
export default {
  name: "Store",
  components: {
    ImageUpload,
    ImagePreview,
    importUploadFile
  },
  data() {
    return {
      showSearch: true,
      visibleImportFile: false,
      fetchFunImport: importStoreList,
      importTemplate: importStoreTemplate,
      tenantList: [],
      subtenantList: [],
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        subTenantId: null,
        tenantId: null,
        id: null,
        code: null
      },
      total: 0,
      tableData: [],
      loading: false,
      dialogTitle: '新增',
      dialogVisible: false,
      dialogParams: {
        type: 1
      },
      storeList: [],
      rules: {
        name: [{ required: true, message: "请输入门店名称", trigger: "blur" }],
        address: [
          { required: false, message: "请输入地址", trigger: "blur" },
        ],
        tenantId: [
          { required: true, message: "请选择商户", trigger: "change" },
        ],
        subTenantId: [
          { required: true, message: "请选择分公司", trigger: "change" },
        ],
        // creditCode: [
        //   {
        //     required: true,
        //     message: "请输入统一社会信用代码",
        //     trigger: "blur",
        //   },
        // ],
        accountName: [
          { required: true, message: "请输入账户名", trigger: "blur" },
        ],
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
        bank: [{ required: true, message: "请输入开户行", trigger: "blur" }],
      },
      emailReg: /^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/,
      creditCode:
        /^(?![\d]+$)(?![a-zA-Z]+$)(?![^\da-zA-Z]+$)([^\u4e00-\u9fa5\s]){15,18}$/,
    };
  },
  created() {
    this.getTableData()
    this.getTenantList()
  },
  methods: {
    async getTableData() {
      this.loading = true
      const res = await getStoreList(this.queryParams)
      this.loading = false
      this.tableData = res.data.list
      this.total = res.data.total
    },
    // 状态
    changeSwitch(data) {
      updateStoreInfo(data).then(res => {
        this.$message({
          message: '操作成功',
          type: 'success'
        });
        this.getTableData()
      })
    },
    async getTenantList() {
      const res = await businessListsAll({ type: 1 })
      this.tenantList = res.data
    },
    async getSubtenantList(type, e) {
      this.dialogParams.subTenantId = null;
      this.getsubtenantListsAll(type, e)
    },
    async getsubtenantListsAll(type, e) {
      let res = {}
      let tenantId
      if (type == 1) {
        tenantId= this.queryParams.tenantId
        res = await subtenantListsAll({ tenantId: tenantId })

      }
      if (type == 2) {
        tenantId=this.dialogParams.tenantId
        res = await subtenantListsAll({ tenantId: tenantId })

      }
      this.subtenantList = res.data;
      let obj = this.tenantList.find(i => i.id == tenantId);
      this.dialogParams.creditCode = obj.creditCode ? obj.creditCode : '';
      this.dialogParams.licence = obj.licence ? obj.licence : '';
    },
    resetQuery() {
      this.queryParams = {
        pageNo: 1,
        pageSize: 10,
      }
      this.getTableData()
    },
    reset() {
      this.dialogParams = {
        type: 1,
        creditCode: undefined,
        licence: undefined,
        tenantId: undefined,
        subTenantId: undefined,
        name: undefined,
        address: undefined,
        userName: undefined,
        phone: undefined,
        email:undefined
      }
    },

    openDialog() {
      this.reset();
      this.dialogVisible = true
      this.dialogTitle = '新增'
    },
    handleConfirm() {
      this.$refs['dialogParams'].validate((valid) => {
        if (valid) {
          if (this.dialogParams.creditCode && !validCreditCode(this.dialogParams.creditCode)) {
            this.$message({
              message: '统一社会信用代码格式不正确',
              type: 'warning'
            });
            return
          }
          if (this.dialogParams.phone && !validMobile(this.dialogParams.phone)) {
            this.$message({
              message: '联系方式格式不正确',
              type: 'warning'
            });
            return
          }
          if (this.dialogParams.email && !validEmails(this.dialogParams.email)) {
            this.$message({
              message: '邮箱格式不正确',
              type: 'warning'
            });
            return
          }
          this.loading = true;
          if (this.dialogParams.id) {
            updateStoreInfo(this.dialogParams).then(res => {
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.getTableData()
              this.dialogVisible = false
              this.loading = false
            }).catch(f => {
              this.loading = false
            })
          } else {
            addStoreInfo(this.dialogParams).then(res => {
              this.$message({
                message: '新增成功',
                type: 'success'
              });
              this.getTableData()
              this.dialogVisible = false
              this.loading = false
            }).catch(f => {
              this.loading = false
            })
          }

        }
      })

    },
    handleUpdate(data) {
      this.reset();
      this.dialogVisible = true
      this.dialogParams = data
      this.dialogTitle = '编辑';
      this.getsubtenantListsAll(2)
    },
    getByIdStoreList(val) {
      console.log(val, '==val')
      getStoreBySuTenantId(this.queryParams.subTenantId).then(res => {
        this.storeList = res.data
      })

    },
    exportList() {
      // 处理查询参数
      let params = { ...this.queryParams }
      params.pageNo = undefined
      params.pageSize = undefined
      let loading
      this.$modal.confirm('是否确认导出所有门店数据项?').then(async () => {
        loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        const res = await exportStoreList(params)
        if (res) {
          this.fileChangeExcel(res, '门店管理')
        }
      }).then(response => {
        loading.close();
      }).catch(() => {
        loading.close();
      })


    },
    // 文件流转excel
    fileChangeExcel(res, name) {
      //1.我们需要通过blob对象来处理，需要模拟一个<a>标签来提供下载链接
      const elink = document.createElement('a');
      elink.style.display = 'none';
      //2.blob是二进制大对象，接受后台返回的数据流，导出数据
      const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      //3.创建一个url 对象，并将blob实例作为参数传入，这样href的值就是以blob开头的一个文件流下载链接,类似于href="blob:http://127.0.0.1xxxxx"
      const blobUrl = URL.createObjectURL(blob);
      elink.href = blobUrl;
      elink.download = name;//下载后的文件名
      //4.将a标签加入body,并手动点击触发下载
      document.body.appendChild(elink);
      elink.click();
      document.body.removeChild(elink);
    },
    handleImportStore() {
      this.visibleImportFile = true
    }
  },
};
</script>

<style lang="less" scoped></style>
